package io.renren.modules.order.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import io.renren.common.utils.CommonUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.modules.area_region.entity.Feedata;
import io.renren.modules.order.entity.V9OrderEntity;
import io.renren.modules.order.service.V9OrderService;
import io.renren.modules.order_pay.entity.V9OrderPayEntity;
import io.renren.modules.order_pay.service.V9OrderPayService;
import io.renren.modules.package_storage.entity.V9PackageStorageEntity;
import io.renren.modules.shipping.entity.V9ShippingEntity;
import io.renren.modules.shipping.service.V9ShippingService;
import io.renren.modules.sys.controller.AbstractController;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;




/**
 * 订单查询
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2019-09-19 17:05:35
 */
@RestController
@RequestMapping("order/v9order")
public class V9OrderController extends AbstractController{
	@Autowired
	private V9OrderService v9OrderService;
	@Autowired
	private IService<V9PackageStorageEntity> v9PackageStorageService;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private V9ShippingService v9ShippingService;
	@Autowired
	private V9OrderPayService v9OrderPayService;

	/**
	 * 列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("order:v9order:list")
	public R list(@RequestParam Map<String, Object> params) {
		PageUtils page = v9OrderService.queryPage(params);
		List<SysUserEntity>kefu=sysUserService.findKefu();
		List<V9ShippingEntity>v9ShippingEntitiesList=v9ShippingService.list(new QueryWrapper<V9ShippingEntity>().eq("enabled", 1).orderByDesc("listorder"));
		return R.ok().put("page", page).put("kefu", kefu).put("shipping", v9ShippingEntitiesList);
	}
	@RequestMapping("/listoutstore")
	public R listoutstore(@RequestParam Map<String, Object> params) {
		PageUtils page = v9OrderService.queryPageOut(params);

		return R.ok().put("page", page);
	}

	/**
	 * 信息
	 */
	@RequestMapping("/info/{orderId}")
	@RequiresPermissions("order:v9order:info")
	public R info(@PathVariable("orderId") Integer orderId) {
		Long adminId=getUserId();
		V9OrderEntity v9Order = v9OrderService.getById(orderId);
		Integer kefuId=v9Order.getKefuId();
		kefuId= (int) (kefuId==0 ? adminId: kefuId);
		v9Order.setKefuId(kefuId);
		Map<String, Object> columnMap = new HashMap<>();
		columnMap.put("order_id", orderId);
		List<V9PackageStorageEntity> listByMap = (List<V9PackageStorageEntity>) v9PackageStorageService
				.listByMap(columnMap);
		columnMap.put("packages", listByMap);
		List<SysUserEntity> kefu = sysUserService.findKefu();
		return R.ok().put("v9Order", v9Order).put("data", columnMap).put("kefu", kefu);
	}
	@RequestMapping("/orderinfo/{orderId}")
	@RequiresPermissions("order:v9order:info")
	public R orderinfo(@PathVariable("orderId") Integer orderId) {
		V9OrderEntity v9Order = v9OrderService.getById(orderId);
		List<V9ShippingEntity>v9ShippingEntitiesList=v9ShippingService.list(new QueryWrapper<V9ShippingEntity>().eq("enabled", 1).orderByDesc("listorder"));
		return R.ok().put("v9Order", v9Order).put("shipping", v9ShippingEntitiesList);
	}
	//改价
	@RequestMapping("/getgaijia/{orderId}")
	public R getgaijia(@PathVariable("orderId") Integer orderId) {
		V9OrderEntity v9Order = v9OrderService.getById(orderId);
		String fee_data=v9Order.getFeeData();
		return R.ok().put("v9Order", v9Order).put("price", fee_data);
	}

	/**
	 * 保存
	 */
	@RequestMapping("/save")
	@RequiresPermissions("order:v9order:save")
	public R save(@RequestBody V9OrderEntity v9Order) {
		v9Order.setPostscript("");
		v9Order.setAdminnote("");
		v9Order.setAddTime(CommonUtils.getCurrentTimeStamp());
		v9OrderService.save(v9Order);

		return R.ok();
	}

	/**
	 * 修改
	 */
	@RequestMapping("/update")
	@RequiresPermissions("order:v9order:update")
	public R update(@RequestBody V9OrderEntity v9Order) {
		v9OrderService.updateById(v9Order);

		return R.ok();
	}

	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("order:v9order:delete")
	public R delete(@RequestBody Integer[] orderIds) {
		v9OrderService.removeByIds(Arrays.asList(orderIds));

		return R.ok();
	}

	@RequestMapping("/changeBiaoji")
	public R changeBiaoji(@RequestParam Map<String, Object> params) {
		Integer orderId = Integer.parseInt((String) params.get("order_id"));
		Integer status = Integer.parseInt((String) params.get("status"));
		V9OrderEntity v9Order = new V9OrderEntity();
		v9Order.setOrderId(orderId);
		v9Order.setSignStatus(status);
		v9OrderService.updateById(v9Order);
		return R.ok();
	}

	@ResponseBody
	@RequestMapping("/getkuaidi")
	public String getPackage(@RequestParam Map<String, Object> params) {
		String type = (String) params.get("type");//
		String postid = (String) params.get("postid");
		String orderSn = (String) params.get("order_sn");
		String key = "zjINYOWH8268";
		//String url = " http://www.kuaidi100.com/query?num=906919164534&key=zjINYOWH8268";
		String url = "https://www.kuaidi100.com/query?type=" + type + "&postid=" + postid;
		return CommonUtils.doGet(url);
	}

	@RequestMapping("/fenbao")
	public R fenbao(@RequestParam Map<String, Object> params) {
		String order_id = (String) params.get("order_id");
		String packid = (String) params.get("packid");
		String[] packidArr = packid.split(",");
		V9OrderEntity order = v9OrderService.getById(Integer.parseInt(order_id));
		order.setOrderId(null);
		String order_sn = CommonUtils.createOrderSn();
		order.setAdminnote("订单" + order.getOrderSn() + "的分包");
		order.setOrderSn(order_sn);
		v9OrderService.save(order);
		order = v9OrderService.getOne(new QueryWrapper<V9OrderEntity>().eq("order_sn", order_sn));
		Integer orderId = order.getOrderId();
		for (int i = 0; i < packidArr.length; i++) {
			Integer pid = Integer.parseInt(packidArr[i]);
			V9PackageStorageEntity entity = new V9PackageStorageEntity();
			entity.setId(pid);
			entity.setOrderId(orderId);
			v9PackageStorageService.updateById(entity);
		}
		return R.ok();
	}

	/**
	 * 根据重量长宽高查询价格
	 *
	 * @param params
	 * @return
	 */
	@RequestMapping("/transport")
	public R transport(@RequestParam Map<String, Object> params) {
		List<Feedata> transInfo = v9OrderService.getTransInfo(params);
		if (transInfo.size() > 0) {
			return R.ok().put("rst", "查询成功").put("info", transInfo);
		} else {
			return R.error();
		}

	}
	@RequestMapping("/getyunfei")
	public R getyunfei(@RequestParam Map<String, Object> params) {
		List<Feedata> transInfo = v9OrderService.getTransInfo2(params);
		if (transInfo.size() > 0) {
			return R.ok().put("rst", "查询成功").put("info", transInfo);
		} else {
			return R.error();
		}

	}

	// 打包
	@RequestMapping("/dabao")
	public R dabao(HttpServletRequest req) throws JSONException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));
		StringBuffer sb = new StringBuffer();
		String s = null;
		while ((s = br.readLine()) != null) {
			sb.append(s);
		}
		JSONObject jsonObject = JSONObject.fromObject(sb.toString());
		String order_id = jsonObject.getString("order_id");
		String fee_data = jsonObject.getString("fee_data");
		String length = jsonObject.getString("length");
		String width = jsonObject.getString("width");
		String height = jsonObject.getString("height");
		String weight = jsonObject.getString("weight");
		String kefu = jsonObject.getString("kefu");
		String kefuId = jsonObject.getString("kefuId");
		String adminnote = jsonObject.getString("adminnote");
		V9OrderEntity v9OrderEntity=v9OrderService.getById(order_id);
		v9OrderEntity.setOrderId(Integer.parseInt(order_id));
		String phpserialze=CommonUtils.jsonArrToPhpSerializer(fee_data);
		v9OrderEntity.setFeeData(phpserialze);
		if (StringUtils.isNotBlank(length)) {
			v9OrderEntity.setLength(Integer.parseInt(length));
		}
		if (StringUtils.isNotBlank(width)) {
			v9OrderEntity.setWidth(Integer.parseInt(width));
		}
		if (StringUtils.isNotBlank(height)) {
			v9OrderEntity.setHeight(Integer.parseInt(height));
		}
		v9OrderEntity.setWeight(new BigDecimal(weight));
		v9OrderEntity.setKefuId(Integer.parseInt(kefuId));
		String note =v9OrderEntity.getAdminnote();//客服备注
		if (StringUtils.isNotBlank(note)) {
			note="["+kefu+"]"+adminnote+"#"+note;
		}else {
			note="["+kefu+"]"+adminnote;
		}
		v9OrderEntity.setAdminnote(note);//客服备注
		v9OrderEntity.setOrderStatus(1);
		v9OrderService.updateById(v9OrderEntity);

//		List<V9PackageStorageEntity> list = v9PackageStorageService.list(new QueryWrapper<V9PackageStorageEntity>().eq("order_id", order_id));
//		for (V9PackageStorageEntity v9PackageStorageEntity : list) {
//			v9PackageStorageEntity.setStatus(1);
//			v9PackageStorageService.updateById(v9PackageStorageEntity);
//		}
		 // CommonUtils.serializeFeeData(fee_data);

		return R.ok();
	}

	@RequestMapping("/fahuo")
	public R fahuo(@RequestBody V9OrderEntity v9Order) {
		v9OrderService.updateById(v9Order);
		return R.ok();
	}
	@RequestMapping("/xianxiapay")
	public R xianxiapay(@RequestBody Map<String, Object> params) {
		Integer orderId=(Integer) params.get("orderId");
		String payfee=(String) params.get("payfee");
		Integer uid=(Integer) params.get("uid");

		V9OrderPayEntity v9OrderPayEntity=new V9OrderPayEntity();
		v9OrderPayEntity.setTotalFee(new BigDecimal(payfee));
		v9OrderPayEntity.setPayFee(new BigDecimal(payfee));
		v9OrderPayEntity.setSpbillno(CommonUtils.createSpbillno());
		v9OrderPayEntity.setPayment("3");
		v9OrderPayEntity.setUserId(uid);
		v9OrderPayEntity.setPayStatus(1);
		v9OrderPayEntity.setOrderStatus(2);
		v9OrderPayEntity.setPayTime(CommonUtils.getCurrentTimeStamp());
		Integer pay_id=v9OrderPayService.insertSelective(v9OrderPayEntity);

		V9OrderEntity v9Order=new V9OrderEntity();
		v9Order.setOrderId(orderId);
		v9Order.setOrderStatus(2);
		v9Order.setPayId(pay_id);
		v9OrderService.updateById(v9Order);
		return R.ok();
	}
	@RequestMapping("/savenote")
	public R saveNote(@RequestParam Map<String, Object> params) {
		String order_id=(String) params.get("order_id");
		String note2=(String) params.get("note");
		V9OrderEntity v9OrderEntity=v9OrderService.getById(order_id);

		SysUserEntity user = getUser();
		String realname=user.getRealname();
		String note =v9OrderEntity.getAdminnote();//客服备注
		if (StringUtils.isNotBlank(note)) {
			note="["+realname+"]"+note2+"#"+note;
		}else {
			note="["+realname+"]"+note2;
		}
		v9OrderEntity.setAdminnote(note);//客服备注
		v9OrderService.updateById(v9OrderEntity);

		return R.ok();
	}


}
